package com.gaohe.interceptor;
import com.alibaba.fastjson.JSON;
import com.gaohe.common.BaseContext;
import com.gaohe.common.PathMatcher;
import com.gaohe.common.R;
import com.gaohe.pojo.Admin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        HttpSession httpSession = request.getSession();
//        1.获取本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求",requestURI);
        //2、判断本次请求是否需要处理
        boolean check = PathMatcher.check(requestURI);
        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            return true;
        }
//        Admin user = (Admin) httpSession.getAttribute("username");
        String auth = request.getHeader("auth");
        Object user = null;
        if(!StringUtils.isEmpty(auth))
        {
//            这里是什么获取
            user = redisTemplate.opsForValue().get("auth"+auth);
        }

//  4、判断登录状态，如果已登录，则直接放行
        if(!StringUtils.isEmpty(user)){
//            将用户id放入线程池中
            BaseContext.setCurrentId((Long)user);
            log.info(requestURI,"用户已登录，放行...");
            return true;
        }
        log.info("用户未登录");
//  5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.setStatus(401);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
